import 'dart:async';
import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:lifecycle/lifecycle.dart';
import 'package:path_provider/path_provider.dart';
import 'app/language/InternationalizationMsg.dart';
import 'app/logger/Logger.dart';
import 'app/routes/app_pages.dart';
import 'app/storage/StorageManager.dart';
import 'app/style/AppStyleThemeData.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await dotenv.load(fileName: ".env.${String.fromEnvironment('ENV_TYPE',defaultValue: 'test')}");
  // initial local storage cache.
  StorageManager.initStorage();


  if (GetPlatform.isAndroid) {
    // 获取应用文档目录路径
    final directory = await getExternalStorageDirectory();
    final logFilePath = '${directory!.path}/app_log.txt';

    // 创建并配置 Logger

    final file = File(logFilePath);
    //initLogger
    Logger.initLogger();

    print('app log path ${file.path}');

    // 自定义日志处理器，将日志写入文件
    logger.onLogged = (log, info) async {
      await file.writeAsString(
        log,
        mode: FileMode.append,
      );
    };
  }


  await ScreenUtil.ensureScreenSize();

  runApp(MyApp());

  //init and config progressing loading dialog.
  configLoading();

}




class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, designSize: const Size(750, 1624));

    return GetMaterialApp(
      title: "WuKong",
      initialRoute: AppPages.INITIAL,
      getPages: AppPages.routes,
      translations: InternationalizationMsg(),
      locale: Locale('zh', 'CN'),  // Get.deviceLocale,  Get.updateLocale(locale);
      fallbackLocale: Locale('zh', 'CN'), // translations will be displayed in that  fallbackLocale: Locale('zh', 'CN'),
      theme: AppStyleThemeData.CustomThemeLight,
      builder: EasyLoading.init(),
      navigatorObservers: [defaultLifecycleObserver],
    );
  }
}


void configLoading() {
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 2000)
    ..indicatorType = EasyLoadingIndicatorType.fadingCircle
    ..loadingStyle = EasyLoadingStyle.dark
    ..indicatorSize = 45.0
    ..radius = 10.0
    ..progressColor = Colors.yellow
    ..backgroundColor = Colors.green
    ..indicatorColor = Colors.yellow
    ..textColor = Colors.yellow
    ..maskColor = Colors.blue.withOpacity(0.5)
    ..userInteractions = true
    ..dismissOnTap = false;
}